package cn.edu.sjtu.FaH.excellent;

import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.*;

import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;

public class HttpUtility {
	public static String postForm(String actionUrl,
			Map<String, String> parameters) throws ClientProtocolException,
			IOException {
		List<BasicNameValuePair> postData = new ArrayList<BasicNameValuePair>();
		for (Map.Entry<String, String> entry : parameters.entrySet()) {
			postData.add(new BasicNameValuePair(entry.getKey(), entry
					.getValue()));
		}

		UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(postData,
				"UTF-8");
		HttpPost post = new HttpPost(actionUrl);
		post.setEntity(formEntity);

		HttpClient httpClient = new DefaultHttpClient();
		HttpResponse response = httpClient.execute(post);
		InputStream inputStream = response.getEntity().getContent();
		StringBuffer content = new StringBuffer();
		BufferedReader bufferedReader = new BufferedReader(
				new InputStreamReader(inputStream));
		String line;
		while ((line = bufferedReader.readLine()) != null) {
			content.append(line);
		}
		bufferedReader.close();
		inputStream.close();
		return content.toString();
	}

	public static String postFormWithFile(String actionUrl,
			Map<String, String> params, Map<String, Bitmap> files)
			throws IOException {
		String boundary = java.util.UUID.randomUUID().toString();
		String prefix = "--", lineEnd = "\r\n";
		String multipartFormData = "multipart/form-data";
		String charset = "UTF-8";

		URL uri = new URL(actionUrl);
		HttpURLConnection conn = (HttpURLConnection) uri.openConnection();
		conn.setReadTimeout(5 * 1000);
		conn.setDoInput(true);
		conn.setDoOutput(true);
		conn.setUseCaches(false);
		conn.setRequestMethod("POST");
		conn.setRequestProperty("connection", "keep-alive");
		conn.setRequestProperty("Charsert", "UTF-8");
		conn.setRequestProperty("Content-Type", multipartFormData
				+ ";boundary=" + boundary);

		StringBuilder builder = new StringBuilder();
		for (Map.Entry<String, String> entry : params.entrySet()) {
			builder.append(prefix);
			builder.append(boundary);
			builder.append(lineEnd);
			builder.append("Content-Disposition: form-data; name=\""
					+ entry.getKey() + "\"" + lineEnd);
			builder.append("Content-Transfer-Encoding:8bit" + lineEnd);
			builder.append(lineEnd);
			builder.append(entry.getValue());
			builder.append(lineEnd);
		}
		DataOutputStream outputStream = new DataOutputStream(conn
				.getOutputStream());
		outputStream.write(builder.toString().getBytes());
		InputStream inputStream = null;
		if (files != null) {
			for (Map.Entry<String, Bitmap> file : files.entrySet()) {
				StringBuilder builder2 = new StringBuilder();
				builder2.append(prefix);
				builder2.append(boundary);
				builder2.append(lineEnd);
				builder2.append("Content-Disposition:form-data;name=\""
						+ file.getKey() + "\";filename=\"" + file.getKey()
						+ ".jpg" + "\"" + lineEnd);
				builder2
						.append("Content-Type:application/octet-stream; charset="
								+ charset + lineEnd);
				builder2.append(lineEnd);
				outputStream.write(builder2.toString().getBytes());
				ByteArrayOutputStream baos = new ByteArrayOutputStream();
				file.getValue().compress(Bitmap.CompressFormat.JPEG, 20, baos);
				inputStream = new ByteArrayInputStream(baos.toByteArray());
				byte[] buffer = new byte[1024];
				int length = 0;
				while ((length = inputStream.read(buffer)) != -1) {
					outputStream.write(buffer, 0, length);
				}

				inputStream.close();
				outputStream.write(lineEnd.getBytes());
			}
		}
		byte[] end_data = (prefix + boundary + prefix + lineEnd).getBytes();
		outputStream.write(end_data);
		outputStream.flush();

		int res = conn.getResponseCode();
		StringBuilder builder3 = new StringBuilder();
		if (res == 200) {
			inputStream = conn.getInputStream();
			int ch;
			while ((ch = inputStream.read()) != -1) {
				builder3.append((char) ch);
			}
		}
		outputStream.close();
		conn.disconnect();
		return builder3.toString();
	}
	
	public static Bitmap getBitmapFromUrl(String imgUrl) {
        URL url;
        Bitmap bitmap = null;
        try {
            url = new URL(imgUrl);
            InputStream is = url.openConnection().getInputStream();
            BufferedInputStream bis = new BufferedInputStream(is);
            bitmap = BitmapFactory.decodeStream(bis);
            bis.close();
        } catch (MalformedURLException e) {
                e.printStackTrace();
        } catch (IOException e) {
                e.printStackTrace();
        }
        return bitmap;
	}
}
